package com.seqb.common.dialect;

import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.file.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
public class UploadImageProcessor extends AbstractElementTagProcessor {

    private static final int PRECEDENCE = 1000;

    public UploadImageProcessor(final String dialectPrefix, final String tagName) {
        super(TemplateMode.HTML, dialectPrefix, tagName, true, null, false, PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler) {
        //获取应用程序的上下文参数
        WebEngineContext webEngineContext = (WebEngineContext) context;
        final String ctx = webEngineContext.getServletContext().getContextPath();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(webEngineContext.getServletContext());

        //获取标签各属性
        Long domainId = null;
        String fileIds = null;

        //获得Thymeleaf标准表达式解析器
        final IStandardExpressionParser parser = new StandardExpressionParser();
        if (StringUtils.isNotEmpty(tag.getAttributeValue("domainId"))) {
            //将属性值解析为Thymeleaf标准表达式
            IStandardExpression evaluableExpression = parser.parseExpression(context, tag.getAttributeValue("domainId"));
            //执行表达工式，获取domainId的值
            domainId = (Long) evaluableExpression.execute(context);
        }
        if (StringUtils.isNotEmpty(tag.getAttributeValue("fileIds"))) {
            //将属性值解析为Thymeleaf标准表达式
            IStandardExpression evaluableExpression = parser.parseExpression(context, tag.getAttributeValue("fileIds"));
            //执行表达工式，获取domainId的值
            fileIds = (String) evaluableExpression.execute(context);
        }

        String domainName = tag.getAttributeValue("domainName");      //获取标签domainName属性
        String domainField = tag.getAttributeValue("domainField");    //获取标签domainField属性
        String domainUpdate = tag.getAttributeValue("domainUpdate");  //获取标签domainUpdate属性
        String isView = tag.getAttributeValue("isView");              //获取标签isView属性

        StringBuffer initImg = null;
        if (domainId != null) {
            FileService fileService = ac.getBean(FileService.class);
            Map<String, Object> params = new HashMap<>(16);
            params.put("pageNumber", 1);
            params.put("pageSize", 1);
            params.put("domainId", domainId);
            params.put("domainName", domainName);
            params.put("domainField", domainField);
            List<FileDO> fileList = fileService.list(params);
            if (fileList != null && fileList.size() > 0) {
                FileDO file = fileList.get(0);
                initImg = new StringBuffer(ctx).append(file.getFileUrl());
            }
        }
        if (!StringUtils.isEmpty(fileIds)) {
            FileService fileService = ac.getBean(FileService.class);
            List<FileDO> fileList = fileService.listByIds(fileIds);
            if (fileList != null && fileList.size() > 0) {
                FileDO file = fileList.get(0);
                initImg = new StringBuffer(ctx).append(file.getFileUrl());
            }
        }
        if (initImg == null) {
            initImg = new StringBuffer(ctx).append("/custom/images/upload.png");
        }
        if (!"true".equals(domainUpdate)) {
            domainId = null;
        }
        StringBuffer html = new StringBuffer();
        html.append("<div class=\"thumbnail\">\r\n");
        html.append("   <img id=\"").append(domainField).append("_img\" src=\"").append(initImg).append("\">\r\n");
        html.append("   <input id=\"").append(domainField).append("_fileId\" name=\"ids\"").append(" class=\"form-control\" type=\"hidden\">\r\n");
        html.append("   <div class=\"caption text-center\">\r\n");
        html.append("       <h3 id=\"").append(domainField).append("_fileName\"></h3>\r\n");
        html.append("       <h3 id=\"").append(domainField).append("_msg\"></h3>\r\n");
        if (!"true".equals(isView)) {
            html.append("       <p><button type=\"button\" class=\"layui-btn layui-btn-sm layui-btn-normal\" id=\"").append(domainField).append("_button\"><i class=\"layui-icon\">\uE654</i>上传图片</button></p>\r\n");
        }
        html.append("   </div>\r\n");
        html.append("</div>\r\n");
        html.append("<script type=\"text/javascript\">\r\n");
        html.append("   layui.use(\"upload\", function () {\r\n");
        html.append("       var upload = layui.upload;\r\n");
        html.append("       var uploadInst = upload.render({\r\n");
        html.append("           elem: \"#").append(domainField).append("_button\", //绑定元素\r\n");
        html.append("           url: ctx+\"/manage/file/file/upload\", //上传接口\r\n");
        html.append("           data: {domainId : \"").append(domainId == null ? "" : domainId).append("\",domainName : \"").append(domainName).append("\",domainField : \"").append(domainField).append("\"},\r\n");
        html.append("           accept: \"images\",\r\n");
        html.append("           acceptMime: \"image/*\",\r\n");
        html.append("           done: function (r) {\r\n");
        html.append("               if(r.code==0){\r\n");
        html.append("                   $(\"#").append(domainField).append("_img\").attr(\"src\", ctx + r.fileUrl);\r\n");
        html.append("                   $(\"#").append(domainField).append("_fileName\").html(r.fileName);\r\n");
        html.append("                   $(\"#").append(domainField).append("_fileId\").val(r.fileId);\r\n");
        html.append("               }\r\n");
        html.append("               else{\r\n");
        html.append("                   this.error(r);\r\n");
        html.append("               }\r\n");
        html.append("           },\r\n");
        html.append("           error: function (r) {\r\n");
        html.append("               $(\"#").append(domainField).append("_img\").attr(\"src\", ctx + \"/custom/images/upload.png\");\r\n");
        html.append("               $(\"#").append(domainField).append("_fileName\").html(\"\");\r\n");
        html.append("               $(\"#").append(domainField).append("_fileId\").val(\"\");\r\n");
        html.append("               $(\"#").append(domainField).append("_msg\").html(r.msg);\r\n");
        html.append("           }\r\n");
        html.append("       });\r\n");

        html.append("   });\r\n");
        html.append("</script>\r\n");

        /**
         * 创建DOM元素模型，修改tag标签的内容
         */
        final IModelFactory modelFactory = context.getModelFactory();
        final IModel model = modelFactory.createModel();
        model.add(modelFactory.createText(html.toString()));
        structureHandler.replaceWith(model, false);
    }

}
